package com.zwj.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import com.zwj.config.comm.MessageBean;
import com.zwj.service.OSSFileUploadService;
import com.zwj.utils.DateCommonUtils;
import io.advantageous.boon.core.Sys;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * OSS对象存储提供[断点续传上传]的方式
 *
 * @author weijun
 */
@Service
public class OSSFileUploadServiceImpl extends OSSFileUploadService {

    private Logger logger = LoggerFactory.getLogger(OSSFileUploadServiceImpl.class);

    @Override
    public MessageBean upload(String filePath) {

        /** 当前系统时间【日期格式：YYYYMMDD】 **/
        String NOW_DATE = DateCommonUtils.currentDay();

        if( StringUtils.isEmpty(filePath) ){
            logger.warn("[{} - OSSFileUploadServer] filePath is null, 要上传的文件路径为空.", NOW_DATE);
            return MessageBean.waring("请选择要上传的文件。", "filePath is null.");
        }

        File uploadFile = new File(filePath);
        if( !uploadFile.isFile() ){
            logger.warn("[{} - OSSFileUploadServer] filePath is not file of path, 要上传的文件路径不是一个文件.", NOW_DATE);
            return MessageBean.waring("请选择要上传的文件。", "filePath is not File.");
        }

        String fileKey = NOW_DATE + "_" + uploadFile.getName();

        //创建OSSClient对象实例
        OSSClient ossClient = super.getOssClientFactory().getInstance();
        if( ossClient == null ){
            logger.error("[{} - OSSFileUploadServer] OSSClient is null, 未能创建OSSClient对象.", NOW_DATE);
            return MessageBean.error("文件上传失败!", "OSSClient is null.");
        }

        // 设置继点续传请求
        UploadFileRequest uploadFileRequest = instanceUploadFileRequest(super.getBucketName(), fileKey);

        if( uploadFileRequest == null ){
            logger.error("[{} - OSSFileUploadServer] UploadFileRequest is null, 未能声明UploadFileRequest继点续传请求.", NOW_DATE);
            return MessageBean.error("文件上传失败!", "UploadFileRequest is initialization of filed, bucketName or yourKey is null.");
        }
        // 指定上传的本地文件
        uploadFileRequest.setUploadFile(filePath);

        UploadFileResult fileResult = null;
        try {
            fileResult = ossClient.uploadFile(uploadFileRequest);
        } catch (Throwable throwable) {
            if( ossClient != null ){
                ossClient.shutdown();
            }
            logger.error("[{} - OSSFileUploadServer] error is {}, 未能声明UploadFileRequest继点续传请求.", NOW_DATE, throwable);
            throwable.printStackTrace();
            return MessageBean.error("服务器比较忙，请稍后重试.");
        }finally {
            if(ossClient != null){
                ossClient.shutdown();
            }
        }

        return MessageBean.success("文件上传成功.", fileResult);
    }

    @Override
    public MessageBean upload(String[] filePaths) {

        /** 当前系统时间【日期格式：YYYYMMDD】 **/
        String NOW_DATE = DateCommonUtils.currentDay();

        if(filePaths == null || filePaths.length == 0 ){
            logger.warn("[{} - OSSFileUploadServer] filePath is null, 要上传的文件路径为空.", NOW_DATE);
            return MessageBean.waring("请选择要上传的文件。", "filePath is null.");
        }

        //创建OSSClient对象实例
        OSSClient ossClient = super.getOssClientFactory().getInstance();

        if( ossClient == null ){
            logger.error("[{} - OSSFileUploadServer] OSSClient is null, 未能创建OSSClient对象.", NOW_DATE);
            return MessageBean.error("文件上传失败!", "OSSClient is null.");
        }

        try {
            File uploadFile = null;

            for(String filepath : filePaths){

                uploadFile = new File(filepath);
                if( !uploadFile.isFile() ){
                    logger.warn("[{} - OSSFileUploadServer] filePath is not file of path, filePath = " + filepath + ",要上传的文件路径不是一个文件.", NOW_DATE);
                    continue;
                }

                String fileKey = NOW_DATE + "_" + uploadFile.getName();

                // 设置继点续传请求
                UploadFileRequest uploadFileRequest = instanceUploadFileRequest(super.getBucketName(), fileKey);

                if( uploadFileRequest == null ){
                    logger.error("[{} - OSSFileUploadServer] UploadFileRequest is null, 未能声明UploadFileRequest继点续传请求.", NOW_DATE);
                    continue;
                }

                // 指定上传的本地文件
                uploadFileRequest.setUploadFile(filepath);

                UploadFileResult fileResult = ossClient.uploadFile(uploadFileRequest);

            }
        }catch (Throwable throwable) {
            if( ossClient != null ){
                ossClient.shutdown();
            }
            logger.error("[{} - OSSFileUploadServer] error is {}, 未能声明UploadFileRequest继点续传请求.", NOW_DATE, throwable);
            throwable.printStackTrace();
            return MessageBean.error("服务器比较忙，请稍后重试.");
        }finally {
            if( ossClient != null ){
                ossClient.shutdown();
            }
        }

        return MessageBean.success("文件上传成功.");
    }

    protected UploadFileRequest instanceUploadFileRequest(String bucketName, String yourKey){

        if( StringUtils.isEmpty(bucketName) || StringUtils.isEmpty(yourKey) ){
            return null;
        }

        // 声明继点续传请求
        UploadFileRequest fileRequest = new UploadFileRequest(bucketName, yourKey);

        // 指定上传并发线程数
        fileRequest.setTaskNum(OSSFileUploadService.UPLOAD_TASK_NUMBER);

        // 指定上传的分片大小
        fileRequest.setPartSize(OSSFileUploadService.UPLOAD_PART_SIZE);

        // 开启断点续传
        fileRequest.setEnableCheckpoint(true);

        return fileRequest;
    }
}
